﻿using System;
using CustomerContactSystem.Core.Infrastructure.Utility;
using CustomerContactSystem.Core.Model;

namespace CustomerContactSystem.WebForms.Enquiries {
    public partial class Create3 : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "type")) {
                return;
            }

            if (Request.QueryString["type"] == "fpoc") {
                FixYourStreetIdCaption.Visible = false;
                FixYourStreetId.Visible = false;
                DeadlineCaption.Visible = false;
                Deadline.Visible = false;
                FixYourStreetWarning.Visible = false;
            }

            GetClassifications();
            GetSources();
            GetReps();
            GetDepartments();
        }

        private void GetClassifications() {
            var enquiryClassifications = EnquiryClassificationRepository.QueryOver().OrderBy(c => c.Classification).Asc.List();
            BindDropDownList(Classifications, enquiryClassifications, "Classification", "Id", "--Select--", "0");
        }

        private void GetSources() {
            var enquirySources = EnquirySourceRepository.QueryOver().OrderBy(s => s.SourceName).Asc.List();
            BindDropDownList(Sources, enquirySources, "SourceName", "Id", "--Select--", "0");
        }

        private void GetReps() {
            var reps = RepRepository.QueryOver().Where(r => r.IsActive).OrderBy(r => r.FirstName).Asc.ThenBy(r => r.SecondName).Asc.List();
            BindDropDownList(Reps, reps, "FullName", "Id", "--Select--", "0");
        }

        private void GetDepartments() {
            var departments = DepartmentRepository.QueryOver().OrderBy(d => d.DepartmentName).Asc.List();
            BindDropDownList(Departments, departments, "DepartmentName", "Id", "--Select--", "0");
        }

        protected void CreateEnquiryNextClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "type")) {
                return;
            }

            var customerId = 0;
            int fysId;
            DateTime deadlineDate;
            var enquiryDate = DateTime.Now;

            if (Request.QueryString["type"] == "ffu") {                
                DateTime.TryParse(Deadline.Text, out deadlineDate);
            }
            else {
                deadlineDate = enquiryDate;
            }

            if (Request.QueryString["customer"] != null) {
                customerId = int.Parse(Request.QueryString["customer"]);
            }

            int.TryParse(FixYourStreetId.Text, out fysId);                       

            var department = DepartmentRepository.LoadReference(int.Parse(Departments.SelectedItem.Value));
            var defaultCategory = GetDefaultCategory(department.Id);

            var enquiry = new Enquiry
                {
                    FixYourStreetId = fysId,
                    DateOfEnquiry = enquiryDate,
                    Classification = EnquiryClassificationRepository.LoadReference(int.Parse(Classifications.SelectedItem.Value)),
                    Category = defaultCategory,
                    Source = EnquirySourceRepository.LoadReference(int.Parse(Sources.SelectedItem.Value)),
                    SubmittedBy = LoggedUser,
                    SubmittedByDepartment = LoggedUser.Department,
                    SubmittedByGroup = LoggedUser.UserGroup,
                    EnquiryDetail = EnquiryDetail.Text.HtmlStripped().Replace("/n", "<br />"),
                    Deadline = deadlineDate,
                    IsMediaEnquiry = IsMediaEnquiry.Checked,
                    IsConfidential = IsConfidential.Checked,
                    CurrentStatus = "Submitted by " + LoggedUser.DisplayName,
                    FirstResponseTime = 0
                };

            if (Reps.SelectedIndex > 0) {
                enquiry.Rep = RepRepository.LoadReference(int.Parse(Reps.SelectedItem.Value));
            }

            if (customerId > 0) {
                enquiry.Customer = CustomerRepository.LoadReference(customerId);
            }

            if (!IsValidObject(enquiry, CreateEnquiryResultMessage)) {
                CreateEnquiryResultMessage.Text = CreateEnquiryResultMessage.Text.Replace("Category is required!", "Department is required!");
                return;
            }

            EnquiryRepository.Add(enquiry);

            enquiry.AddHistory(enquiry.DateOfEnquiry, enquiry.CurrentStatus);

            if (Tags.Text.Trim().Length > 0) {
                var tagsList = Tags.Text.Split(',');
                foreach (var tagName in tagsList) {
                    enquiry.AddTag(LoggedUser.DisplayName, GetOrCreateTag(tagName));
                }
            }

            EnquiryRepository.Update(enquiry);
            Response.Redirect("~/Enquiries/Create4.aspx?id=" + enquiry.Id + "&type=" + Request.QueryString["type"]);
        }

        private EnquiryCategory GetDefaultCategory(int departmentId) {
            if (departmentId == 0) {
                return null;
            }

            var defaultCategory =
                EnquiryCategoryRepository.QueryOver().Where(
                    c => c.CategoryName == "General" && c.Department.Id == departmentId).SingleOrDefault();

            if (defaultCategory == null) {
                defaultCategory = new EnquiryCategory
                    {
                        AvailableForSelection = true,
                        CategoryName = "General",
                        Department = DepartmentRepository.LoadReference(departmentId)
                    };
                EnquiryCategoryRepository.Add(defaultCategory);
            }

            return defaultCategory;
        }

        private Tag GetOrCreateTag(string tagName) {
            var foundTag = TagRepository.QueryOver().Where(t => t.TagName == tagName).SingleOrDefault();
            if (foundTag == null) {
                foundTag = new Tag
                    {
                        TagName = tagName
                    };
                TagRepository.Add(foundTag);
            }
            return foundTag;
        }
    }
}